package com.newki.auth.mvi.vm

import com.android.basiclib.base.mvi.BaseEISViewModel
import com.android.basiclib.bean.OkResult
import com.android.basiclib.utils.log.MyLogUtils
import com.google.gson.Gson
import com.newki.auth.mvi.eis.AuthEffect
import com.newki.auth.mvi.eis.AuthIntent
import com.newki.auth.mvi.eis.AuthUiState
import com.newki.auth_api.entity.EmployerEntity
import com.newki.profile_api.router.ProfileServiceProvider
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val mGson: Gson,
) : BaseEISViewModel<AuthEffect, AuthIntent, AuthUiState>() {

    override fun initUiState(): AuthUiState = AuthUiState.INIT

    override fun handleIntent(intent: AuthIntent) {
        when (intent) {
            is AuthIntent.FetchArticle -> fetchArticle()
            is AuthIntent.TestGson -> testGson(intent.gson)
        }
    }

    /**
     * 测试 Gson
     */
    private fun testGson(innerGson: Gson) {

        MyLogUtils.w("是否是同一个Gson:${innerGson == mGson}")

        launchOnUI {

            sendEffect(AuthEffect.ToastMessage("是否是同一个Gson:${innerGson == mGson}"))

            val json = """
    {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
""".trimIndent()

            val employer = withContext(Dispatchers.IO) {
                mGson.fromJson(json, EmployerEntity::class.java)
            }

            MyLogUtils.w("employer:$employer")
        }
    }


    private fun fetchArticle() {

        launchOnUI {

            loadStartLoading()

            val articleResult = ProfileServiceProvider.profileService?.fetchUserProfile()

            if (articleResult is OkResult.Success) {
                //成功
                loadSuccess()

                sendUiState(AuthUiState.SUCCESS(articleResult.data))

//                updateUiState {
//                    copy(articleUiState = ArticleUiState.SUCCESS(articleResult.data))
//                }

            } else {
                val message = (articleResult as OkResult.Error).exception.message
                sendEffect(AuthEffect.ToastMessage(message))
            }

        }

    }

}